package com.mapforge.collection;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

import com.mapforge.selection.ComparablePoint;

public class ComparablePointPool extends AbstractCache<ComparablePoint> {
	List<ComparablePoint> points;
	int maximumCacheSize;

	public ComparablePointPool(int maximumCacheSize) {
		super(new Factory<ComparablePoint>() {
			@Override
			public ComparablePoint createInstance() {
				return new ComparablePoint();
			}
		});
		this.maximumCacheSize = maximumCacheSize;
		points = new ArrayList<ComparablePoint>();
	}

	@Override
	public boolean isEmpty() {
		return points.isEmpty();
	}

	@Override
	protected ComparablePoint getCachedInstance() {
		if (points.size() == 0) {
			throw new NoSuchElementException(
					"Unable to return a chached instance");
		}
		return points.get(0);
	}

	@Override
	public boolean cacheInstance(ComparablePoint t) {
		if (t == null) {
			throw new NullPointerException("Cannot cache null instances");
		}
		if (points.size() >= maximumCacheSize) {
			return false;
		} else {
			return points.add(t);
		}
	}
}
